//获取历史聊天信息,渲染
function getHistoryMsg() {
	var params = {
    roomId: log_id
	}
	newAjaxPost("/h5/rcs/chat-history", params, getHistoryMsgOk);
}
function getHistoryMsgOk(res) {
  console.log(res,'聊天记录')
	var onemsg = '';
	var history = res.data;
	if (history.length > 0) {
		for (var i = 0; i < history.length; i++) {
			if($("#" + history[i].id).html()) {
				continue
			}

			if (history[i].userId == patientIM) {	//自己发的信息
				if (history[i].msgType == 3) {				//自己发过的图片
					onemsg += `
						<div class="onemsgUser1 onemsgUser ${history[i].isRead == 0 ? 'notRead' : 'isRead'}" style="display: flex; flex-direction: row-reverse; padding-right: 5px;" id="${history[i].id}" type="${history[i].msgType}">
							<div class="msgImgDiv" style="padding: 16px 0px;">
								<img class="msgImg" src = "${patientImg}" style="width: 30px;"></img>
							</div>
							<div class="msgPDiv" style="background: #2b73cc; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%; position: relative;">
								<p class="msghead" style="color:white;">[${truename}] ${history[i].msgDate}</p>
								<p class="msgbody">
									<img class="msgImg openBig" src="${history[i].msgText}"></img>
								</p>
								<div class="delete_btn" id="id${history[i].id}" num="${history[i].id}" date="${history[i].msgDate}">撤回</div>
							</div>
						</div>`
				} else if (history[i].msgType == 0) {				//自己发过的消息
					onemsg += `
						<div class="onemsgUser1 onemsgUser ${history[i].isRead == 0 ? 'notRead' : 'isRead'}" style="display: flex; flex-direction: row-reverse; padding-right: 5px;" id="${history[i].id}">
							<div class="msgImgDiv" style="padding: 16px 0px;">
								<img class="msgImg" src = "${patientImg}" style="width: 30px;"></img>
							</div>
							<div class="msgPDiv" style="background: #2b73cc; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%; position: relative;">
								<p class="msghead" style="color:white;">[${truename}] ${history[i].msgDate}</p>
								<p class="msgbody">
									<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;color:white;">${history[i].msgText}</pre>
								</p>
								<div class="delete_btn" id="id${history[i].id}" num="${history[i].id}" date="${history[i].msgDate}">撤回</div>
							</div>
						</div>`
				} else if (history[i].msgType == 4) {		//自己撤回的消息
					onemsg += `
						<div class="onemsgUser1" style="width: 100%;" id="${history[i].id}">
							<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px auto;text-align: center; font-size: 12px; max-width: 60%;">
								<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;">${history[i].msgText}</pre>
							</div>
						</div>`
				}
				else if (history[i].msgType == 6) {
					if (history[i].msgText.indexOf("和患病时长【起病至就诊的时间】") != -1 || history[i].msgText.indexOf("医生已结束问诊") != -1) {
						onemsg += `
							<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
								<div class="msgImgDiv" style="padding: 16px 0px;">
									<img class="msgImg" src =${doctorHeadImg} style="width: 30px;"></img>
								</div>
								<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
									<p class="msghead" style="color:black;">[${oldDoctorName}] ${history[i].msgDate}</p>
									<p class="msgbody">
										<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #353535;">
											${history[i].msgText}</pre>
									</p>
								</div>
							</div>`
					}
					else if (history[i].msgText.indexOf("回答完毕记得点击下方【已完成") != -1) {
						onemsg += `
							<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
								<div class="msgImgDiv" style="padding: 16px 0px;">
									<img class="msgImg" src =${doctorHeadImg} style="width: 30px;"></img>
								</div>
								<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
									<p class="msghead" style="color:black;">[${oldDoctorName}] ${history[i].msgDate}</p>
									<p class="msgbody">
										<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #353535;">
											${history[i].msgText}
										</pre>
										<p style="width:20%;text-align: center;background: #1189FF;border-radius: 6px;font-size: 14px;font-family: PingFang SC;font-weight: bold;
											color: #FEFEFE;margin:5px 0;padding:5px 2px" id="isFinish" inquiryLogId=${history[i].inquiryLogId}>已完成</p>
									</p>
								</div>
							</div>`
					}
					else if (history[i].msgText.indexOf("您可选择离线等待本次问诊哦！") != -1) {
						onemsg += `
							<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
								<div class="msgImgDiv" style="padding: 16px 0px;">
									<img class="msgImg" src=${doctorHeadImg} style="width: 30px;"></img>
								</div>
								<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
									<p class="msghead" style="color:black;">[${oldDoctorName}] ${history[i].msgDate}</p>
									<p class="msgbody">
										<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #353535;">${history[i].msgText}</pre>
									</p>
								</div>
							</div>`
					}
				}
			}
			else {								//对方发的信息
				if (history[i].msgType == 5) {	//系统消息
					onemsg += `
						<div class="onemsg" style="width: 98%;padding-left: 5px;" id="${history[i].id}">
							<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px auto;text-align: center; font-size: 12px; max-width: 60%;">
									<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;">${history[i].msgText}</pre>
							</div>
						</div>`
				}
				else {
					onemsg += `
						<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
							<div class="msgImgDiv" style="padding: 16px 0px;">
								<img class="msgImg" src="${doctorHeadImg}" style="width: 30px;"></img>
							</div>
							<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
								<p class="msghead" style="color:black;">[${history[i].msgUserName}] ${history[i].msgDate}</p>
								<p class="msgbody">`
					if (history[i].msgType == 3) {
						onemsg += `	<img class="msgImg openBig" src="${history[i].msgText}"></img>`
					} else {
						onemsg += `	<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;">${history[i].msgText}</pre>`
					}
					if (/(请等待药师审核|药师已审核通过)/.test(history[i].msgText)) {
						onemsg += `	<p style="font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #1189FF;" class="goList">查看处方等清单></p>`
					}
					onemsg += `		
								</p>
							</div>
						</div>`
				}
			}
		}
		$("#chat_Log").append(onemsg);

		$(".goList").click(function () {
			// var inquiryLogId = $(this).attr("inquiryLogId")

			// goPage("my_prescription_list.htm?logId=" + inquiryLogId)
			goPage("my_prescription_list.htm?logId=" + log_id)
		})

		if (inquiryType == 3 || inquiryType == 4) {
			var finishBtn = document.querySelectorAll("#isFinish")
			if (isCompleted == 1) {
				//已经填了已完成
				finishBtn.forEach((item) => {
					item.style.background = '#F6F6F6'
					item.style.color = '#1189FF'
					item.click = null;
				})
			} else {
				//点击发送已完成信息
				var time = formatDate(new Date());
				finishBtn.forEach((item, index) => {
					if (index == (finishBtn.length - 1)) {
						item.addEventListener('click', () => {
							parent.wsConnection.send(30, {
								"logId": log_id, //问诊[id
								"userIm": patientIM, // 患者im
								"doctorIm": doctor_imid, // 医生imID
							})
							parent.wsConnection.send(3, {
								'msgText': "医生已经收到您的信息啦~若医生还没回复，您可选择离线等待本次问诊哦！", // 信息体
								'friendId': patientIM, // 患者imID
								'inquiryLogId': log_id, //问诊iD log_id
								'msgusername': truename, //医生名字
								'msgType': 6,
								'msgDate': time
							})
							getInquiryLogDetails()
							getHistoryMsg()
						})
					} else {
						item.style.background = "#F6F6F6";
						item.style.color = "#1189FF";
						item.click = null;
					}
				})
			}
		}
		else {
			var finishBtn = document.querySelectorAll("#isFinish")
			finishBtn.forEach((item) => {
				item.style.background = '#F6F6F6'
				item.style.color = '#1189FF'
				item.click = null;
			})
		}

		$(".goList").click(function () {
			goPage("my_prescription_list.htm?logId=" + log_id)
		})
		// 300ms后,等待图片加载完，滚动条自动滚动到底部
		setTimeout(function () {
			scrollBottom()
			$(".openBig").on('click', function () {
				var imgsrc = $(this)[0].src
				$('.show').attr('src', imgsrc)
				$('.img_mask').addClass('weui-mask--visible');
				$('.img_dialog').addClass('weui-dialog--visible');
			})
			$(".close_img").on('click', function () {
				$('.img_mask').removeClass('weui-mask--visible')
				$('.img_dialog').removeClass('weui-dialog--visible')
			})
		}, 300);
	}
}

// 输入法遮掩聊天板内容（未完成）/判断是否TV端
function calChatHeight() {
	var winH = $(window).height();
	var chatH;
	if (Number(log_type) == '1') {			//视频
		chatH = winH - 340;
		// $('#divCameraMic').show().css('visibility', 'visible');
		// $("#footer").css("position","static");
		// $('#divChatLog').css("margin-top", "167px");
	} else {							//图文
		chatH = winH - 100;
		// $('#divCameraMic').hide();
		// $("#footer").css("position","absolute");
		// $('#divChatLog').css("margin-top", "0px");
	}
	//alert(chatH);
	// $('#chat_Log').height(chatH);
}

// 根据图片上传状态修改提示语
var uploadingPic = false
//图片
$(function () {
	var tmpl = '<div style="width:79px;height:79px;margin-top:30px;float: left;margin-right:20px;position: relative;"><div class="picClose" style="position: absolute;width: 20px;top: -10px;right: -10px;"><img width="100%" src="../res/images/close.jpg"></div><li class="weui-uploader__file" style="background-image:url(#url#)"></li></div>',
		$gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
		$galleryImgShow = $("#gallery_img_show"), $galleryShow = $("#gallery_show"),
		$uploaderInput = $("#uploaderInput"), $uploaderFiles = $("#uploaderFiles");
	var $galleryImg = $(".weui-gallery__img"); //相册图片地址
	var $gallery = $(".weui-gallery");
	$uploaderInput.on("change", function (e) {
		var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
		var file = e.target.value;
		var formData = new FormData();
		//获取当前时间戳加上获取的文件后缀 为文件名
		var filename = new Date().getTime() + getSuffix(file);
		var str = filename.substring(filename.length - 4);
		if (str != '.gif' && str != 'jpeg' && str != '.jpg' && str != '.png') {
			msgInfo('请上传图片格式的文件！')
			return
		}
		$(".weui-uploader__input-box").hide()
		uploadingPic = true
		//注意formData里append添加的键的大小写
		formData.append('key', ossdata.dir + filename); //存储在oss的文件路径
		formData.append('OSSAccessKeyId', ossdata.accessid); //accessKeyId
		formData.append('policy', ossdata.policy); //policy
		formData.append('Signature', ossdata.signature); //签名
		formData.append('callback', ossdata.callback); //签名
		//如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
		formData.append("file", e.target.files[0]);
		formData.append('success_action_status', 200); //成功后返回的操作码
		var fileUrl = ossdata.host + '/' + 'ceshi/' + filename;
		$.ajax({
			type: 'POST',
			data: formData,
			processData: false,//这里默认为true,必须手动改为false
			contentType: false,//这里必须手动改为false,避免出现解析错误
			cache: false,//缓存必须改为false,保证每次都能读取最新数据
			url: ossdata.host,
			success: function (res) {
				if (res.code == 1) {		//上传成功
					msgInfo('图片上传成功', 1200);
					Picdata = res.data
					uploadingPic = false
				}
			},
			error: function (error) {
				console.log(error);//文件上传失败打印错误信息
				$(".weui-uploader__input-box").show()
				uploadingPic = false
			}
		})
		for (var i = 0, len = files.length; i < len; ++i) {
			var file = files[i];
			if (url) {
				src = url.createObjectURL(file);
			} else {
				src = e.target.result;
			}
			$uploaderFiles.html($(tmpl.replace('#url#', src)));
		}
	});

	$uploaderFiles.on("click", "li", function () {
		$galleryImg.attr("style", this.getAttribute("style"));
		$gallery.fadeIn(100);
	});
	$gallery.on("click", function () {
		$gallery.fadeOut(100);
	});
	$uploaderFiles.on("click", ".picClose", function () {
		console.log(1)
		Picdata = ''
		$(".weui-uploader__input-box").show()
		$("#uploaderFiles").html('');
	});
})

function saveImg() {
	if (!Picdata) {
		msgInfo(uploadingPic ? '请等待图片上传完毕' : '请先上传图片', 1000)
		return;
	}
	newUpdateUserHeadImg(Picdata)
}

// 判断是否ios
function checkWxAndIos() {
	var u = navigator.userAgent;
	var ua = navigator.userAgent.toLowerCase();
	var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	if (isIOS)
		return true;
	else
		return false;
}

function formatDate(date, format) {
	if (format === undefined) {
		format = 'YY-MM-DD hh:mm:ss';
	}

	var year = date.getFullYear(),
		month = date.getMonth() + 1,//月份是从0开始的
		day = date.getDate(),
		hour = date.getHours(),
		min = date.getMinutes(),
		sec = date.getSeconds();
	var preArr = Array.apply(null, Array(10)).map(function (elem, index) {
		return '0' + index;
	});
	var newTime = format.replace(/YY/g, year)
		.replace(/MM/g, preArr[month] || month)
		.replace(/DD/g, preArr[day] || day)
		.replace(/hh/g, preArr[hour] || hour)
		.replace(/mm/g, preArr[min] || min)
		.replace(/ss/g, preArr[sec] || sec);

	return newTime;
}
